var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var WxParse = require('../../wxParse/wxParse.js');
var base64 = require('../../utils/Base64.js');
var topictitle ="";
var topicid = "";
var app = getApp();
var uid = '';
var uname = '';  //作者用户名
var wxAuthFail = true;
var inviteuid = 0;
var linkcode = '';

var detailMessage = '';

Page({
  data: {
    util: util,
    host: util.api_host,
    tc: 0,
    my_cion: 88,

    indicatorDots: true,
    autoplay: true,
    interval: 4000,
    duration: 600,
    swiper_w:0,
    swiper_h:0,

    video_w: 300,
    video_h: 165,

    detailShouhou: '',//售后保障
    
      data:{},
      likeuser: [],
      detailMessage: '',
      pinHistoryData:[], //拼单历史
      imgDomain: app.globalData.imgDomain,
      isFollow: false, //是否已关注
      isLiked: false, //是否已赞
      uid:'',  //当前登录用户Id
      token:'', //post请求时，当前登录用户token
      loginUname:'', //当前登录用户名
      commentMsg : '',
      replyid:0, //当前被回复的评论id
      openid:'',
      topicid:0,
      startTime: 0,
      hasShare: false,
      tuid:0,
      firstImgUrl:'',
      canEdit: false,
      isShow: false,

      isIphone: false,

      isOnLoad:false,

      modalHidden: true,

      guigeData: [],
      selectGuige: '',

      gwc_count: 0,

      countValue: 1,

      curr: {
        goods_info:"curr",
        pinglun: "",
        shouhou: ""
      },

      contact_phone: '',

      commentList: [],
      colorSet: '',

      ghs_info: '',
      isService:false,
      hide_commentview:true,

      topictitle:'',

    yuding_width: 160
  },
  
  onLoad: function(data){
    var tc = app.get_tc();
    var that = this;
    topictitle = data.topictitle;
    that.setData({
      tc: tc,
      topictitle: topictitle,
      brtime: data.brtime,
      btype: data.btype,
    });
    wx.showLoading({
      title: tc == 1 ?'加載中':'加载中',
      mask: 'true'
    });
    
    // var titlename = tc == 1 ? '詳情' : '详情';
    wx.setNavigationBarTitle({
      title: topictitle,
    });
    var that = this;
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });
    that.setData({
      windowWidth: wx.getSystemInfoSync().windowWidth,
      windowHeight: wx.getSystemInfoSync().windowHeight
    }) 
    wx.getSystemInfo({
      success: function (res) {
        var isiPhone = (res.model.indexOf('iPhone') >= 0);
        // var height = res.windowWidth * 2 / 3;
        var height = res.windowWidth;
        var v_w = res.windowWidth;
        // v_w =  v_w - 25;
        var v_h = v_w * 4/ 7;
        that.setData({
          isIphone: isiPhone,
          swiper_w: res.windowWidth,
          swiper_h: height,
          video_w: v_w,
          video_h: v_h,
          goodsImgView_h: (res.windowWidth - 30) / 2,
          tc: tc,
          yuding_width: (res.windowWidth - 160)
        });
      }
    })

    var gwc_datas = wx.getStorageSync('gwc_datas');
    if (!gwc_datas) {
      gwc_datas = [];
    }
    this.setData({
      gwc_count: gwc_datas.length
    });

    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck",
        "tc": that.data.tc
      },
      success: function (responseData) {
        console.log("==kankanshishenm====",responseData);
        that.setData({
          isShow: responseData.data.isShow
        });
      }
    });

    topicid = data.topicid || "";
    //是否是从 别人分享的 页面点进来的
    inviteuid = data.inviteuid ? data.inviteuid : '';
    var pages = getCurrentPages();
    var curPageIndex = pages.length;
    //如果是分享进来 或者 当前栈下标 是 1 都认为是分享进来的  因为分享人可能没授权登录 无法分享邀请码
    var isShare = (inviteuid || curPageIndex <= 1);
    this.setData({
      hasShare: isShare,
      topicid: topicid,
      isOnLoad: true
    })
    
    //获取商品32位唯一id，用户商品三级分销
    linkcode = data.linkcode ? data.linkcode : '';
    //调用应用实例的方法获取全局数据
    that.getLoginInfo();
    //获取售后保障
    // this.getShouhouMsg();

    // this.load();

    app.getAllAbout('contact', function (res) {
      that.setData({
        contact_phone: res
      })
    });
  },

  onShow:function(){
    // if(!this.data.isOnLoad){
    //   this.load();
    // }
    this.setData({
      isOnLoad: false,
    })
  },

  //获取售后保障介绍
  getShouhouMsg: function(){
    var that = this;
    
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "shouhou",
        "uid": util.orgid
      },
      success: function (responseData) {
        console.log("售后保障：", responseData);
        that.setData({
          detailShouhou: responseData.data.msg,
        });
        /** 
        * WxParse.wxParse(bindName , type, data, target,imagePadding) 
        * 1.bindName绑定的数据名(必填) 
        * 2.type可以为html或者md(必填) 
        * 3.data为传入的具体数据(必填) 
        * 4.target为Page对象,一般为this(必填) 
        * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选) 
        */
        WxParse.wxParse('detailShouhou', 'html', that.data.detailShouhou, that, 12); 
      }
    });
  },


  load:function(){
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topicdetail",
      linkcode: linkcode,
      inviteuid: inviteuid,
      loginuid: that.data.uid ? that.data.uid : '',
      topicid: topicid
    };
    console.log("动态详情请求参数：", params);
    //动态详情
    util.api({
        data:params,
        success:function(responseData){  
          var data = responseData.data;
          console.log("啊啊啊啊啊详情：", data);

          if (uid == data.user.uid) {
            that.setData({
              canEdit: true
            })
          }
          

          //供货商信息
          if (data.orgid) {
            app.GetUserInfo(data.orgid, function (res) {
              console.log("供货商信息：", res);
              that.setData({
                ghs_info: res
              })
            });
          }

          //处理时间
          var date = new Date(data.dateline*1000);
          data.formatDate = date.getFullYear()+"-"+(Number(date.getMonth())+1)+"-"+date.getDate();
          //处理语音
          if(data.audio) {                
              data.formatAudio = JSON.parse(data.audio);
          }
          //处理视频
          if (data.video) {
            var videolinks = data.video.split(",");
            var len = videolinks.length;
            var tx_videolinks = [];
            for (var i = 0; i < len; i++) {
              if (videolinks[i].indexOf('v.qq.com') > 0) {
                tx_videolinks = tx_videolinks.concat(videolinks[i])
              }
            }
            len = tx_videolinks.length;
            var videoSrcs = new Array(len);
            var count = 0;
            for (var i = 0; i < len; i++) {
              app.getVideoSrcLink(i, tx_videolinks[i], function (url, index) {
                count++;
                if (url != -1) {
                  videoSrcs[index] = url;
                }
                if (count >= len) {
                  var videoSrcArr = [];
                  for(var n = 0; n < len; n++){
                    if(videoSrcs[n]){
                      videoSrcArr = videoSrcArr.concat(videoSrcs[n]);
                    }
                  }
                  that.setData({
                    videolinkArray: videoSrcArr
                  });
                }
                
              });
            }
          }
          //处理message  
          detailMessage = data.message;
          // detailMessage = data.message.replace(/\n/g, '<br />');
          // console.log("detailMessage: ", detailMessage);
          
          that.setData({
            detailMessage: data.message,
          }); 
          /** 
          * WxParse.wxParse(bindName , type, data, target,imagePadding) 
          * 1.bindName绑定的数据名(必填) 
          * 2.type可以为html或者md(必填) 
          * 3.data为传入的具体数据(必填) 
          * 4.target为Page对象,一般为this(必填) 
          * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选) 
          */
          WxParse.wxParse('detailMessage', 'html', detailMessage, that, 12); 
          // data.message = data.message.replace(/&nbsp;/g, '');
          
          topictitle = data.topictitle;
          uname = data.user.username;
          
          var f_imgUrl = '';
          if (data.photoscbk && data.photoscbk.length > 0){
            var firstImageInfo = data.photoscbk[0];
            if (firstImageInfo) {
              f_imgUrl = firstImageInfo.photo + "!120a";
            }
          }
          console.log("第一张图片链接：", f_imgUrl);
          that.setData({
              data:data,
              likeuser: data.likeuser,
              isLiked:data.isLiked,
              tuid:data.postuid,
              firstImgUrl: f_imgUrl
          });          
          //当前用户是否已关注作者
          // that.isFollow(uid, data.postuid);
          
          wx.hideLoading();
          

          that.getAttributeForHotel()
          // 获取门店
          that.getghs();
          that.loadCommentList(topicid, 1);
          that.getKucunToday(data.id)
        }
    });
  },

  //读取所有评论
  loadCommentList: function(gid, page){
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiccommentlist",
        id: gid,
        page: page,
        num:10
      },
      success: function (responseData) {
        var data = responseData.data;
        console.log("商品评论：", data);
        if (data && data.length > 0) {
          data.forEach(function (m, i) {
            m.date = util.formatTime(new Date(parseInt(m.dateline) * 1000), '-', ':');
          });
          that.setData({
            commentList: data
          });
        }
      }
    });
  },

  //重新读取 登录用户信息
  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },
  getLoginInfo:function(){
    var that = this;
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        
        //更新数据
        wxAuthFail = false;
        uid = res.uid;
        that.setData({
          userInfo:res,
          uid: res.uid,
          token: res.token,
          loginUname: res.uname,
          openid: res.wxsmall_openid
        })

        that.load();

        var canEdit = false;
        if (that.data.data && that.data.data.user && res.uid == that.data.data.user.uid) {
          canEdit = true;
        }
        //设置用户信息
        app.GetUserInfo(res.uid, function (u_res) {
          console.log("getUserInfo:", u_res);
          //更新数据
          that.setData({
            canEdit: canEdit ? canEdit : u_res.isgroup == 1
          })
        });
      } else {
        that.load();
        wxAuthFail = true;
      }
    }, inviteuid)
  },

  

 
  //评论
  inputMessage: function(e) {
    //把评论内容绑定到提交按钮上
    var val = e.detail.value;
    this.setData({
        commentMsg: val
    })
  },
  changeReplyid: function(e) {
    var val = e.currentTarget.dataset.id;
    var replyusername = e.currentTarget.dataset.uname;
    this.setData({
        replyid: val,
        commentMsg: this.data.tc == 1 ?'@回復':'@回复'+replyusername +':'    
    })  
  },


  inputFinish: function (e) {
    var comment = e.detail.value;
    console.log("输入信息：" + comment);
    this.setData({
      commentValue: comment
    })
  },
  showCommentView: function (e) {
    this.setData({
      hide_commentview: false,
      data_id: e.currentTarget.dataset.id
    })
  },
  hideCommentView: function () {
    this.setData({
      hide_commentview: true
    })
  },
  addComment: function(e) {
    if (wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }

      var that = this;
      var uid = e.currentTarget.dataset.uid ? e.currentTarget.dataset.uid : that.data.uid;
      var token = e.currentTarget.dataset.token ? e.currentTarget.dataset.token : that.data.token;
      var catatype = e.currentTarget.dataset.catatype;
      var replyid = e.currentTarget.dataset.replyid;
      var message = e.currentTarget.dataset.message ? e.currentTarget.dataset.message : that.data.commentValue;
      if(!message) {
        app.dialog(that.data.tc == 1 ? '請輸入內容' :'请输入内容', 'loading');
          return;
      }
      var privatekey = utilMd5.hexMD5(uid+'topiccomment'+token);
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"topiccomment",
            uid:uid,
            id:topicid,
            type:catatype,
            replyid:replyid,
            message:message,
            privatekey: privatekey
        },
        method:'POST',
        success:function(responseData){
            var data = responseData.data;
            var txt = replyid > 0 ? (that.data.tc == 1 ? '回復' : '回复') : (that.data.tc == 1 ? '評論' :'评论');
            if(data.msg === "true") {                
                that.setData({
                    isLiked: true
                });
                that.setData({
                    commentMsg: ''
                })

                app.dialog(txt + that.data.tc == 1 ? '成功' :'成功', 'success',that.refreshPage());
            } else {
              app.dialog(txt + that.data.tc == 1 ? '失敗' :'失败', 'loading');
            }
        }
    });
  },
  //投诉
  complain: function(e) {
    app.dialog(this.data.tc == 1 ? '投訴成功' :'投诉成功', 'success');
  },
  //页面分享
  onShareAppMessage: function () {
    var invUid = this.data.uid? this.data.uid : '';
    var linkcode = this.data.data.linkcode ? this.data.data.linkcode : linkcode;
    var path = '/pages/hotel-detail/hotel-detail?topicid=' + topicid + '&inviteuid=' + invUid + "&linkcode=" + linkcode;
    console.log("分享给好友：" + path); 
    return {
        title: topictitle?topictitle:uname,
        path: path
    };
  },

  copyLink:function(){
    var that = this;
    wx.setClipboardData({
      data: that.data.data.alt,
      success: function (res) {
        wx.showToast({
          title: that.data.tc == 1 ?'已復制到剪貼板':'已复制到剪贴板',
        })
      }
    })
  },

  
  shareToPengyouquan: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log('海报图片链接：' + e.currentTarget.dataset.imgsrc);

    // shareImgUrl = base64.encode(shareImgUrl);
    // var url = "/pages/haibao-page/haibao-page?imgUrl=" + shareImgUrl;
    // wx.navigateTo({ url: url });
    
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },

  showEWM: function (e) {
    wx.previewImage({
      current: e.currentTarget.dataset.imgsrc,
      urls: [e.currentTarget.dataset.imgsrc]
    })
  },
  //刷新当前页
  refreshPage: function() {
      wx.redirectTo({
        url:'/pages/hotel-detail/hotel-detail?topicid='+topicid
      })
  },




  buyAction: function(e){
    if (this.data.guigeData.length > 0 && !this.data.selectGuige){
      var toastStr = this.data.tc == 1 ? "請選擇" :"请选择 " + this.data.data.guige; 
      wx.showModal({
        title: this.data.tc == 1 ? '提示' :"提示",
        content: toastStr,
        showCancel: false
      })
    } else {
      var goodsInfo = {};
      goodsInfo.id = this.data.data.id;
      goodsInfo.ghsid = this.data.data.postuid;
      goodsInfo.title = this.data.data.topictitle;
      goodsInfo.titleofenglish = this.data.titleofenglish;
      goodsInfo.def_img = this.data.data.photoscbk[0].photo;
      goodsInfo.sel = true;
      goodsInfo.guigeName = this.data.data.guige ? this.data.data.guige : '';
      goodsInfo.selGuige = this.data.selectGuige;
      if (this.data.data.pin == 1) {//拼单商品
        goodsInfo.price = this.data.data.pinprice;
      } else {
        goodsInfo.price = this.data.selectGuige ? this.data.selectGuige.price : this.data.data.sellprice;
      }
      goodsInfo.yunfei = this.data.data.yunfei;
      goodsInfo.kucun = this.data.data.kucun;
      goodsInfo.buycount = this.data.countValue;
      goodsInfo.source = this.data.data.source;
      goodsInfo.pin = this.data.data.pin;//这里加是否是拼单商品标记
      goodsInfo.pinzong = this.data.data.pinzong;//这个是拼单的 期数，通常一天为一个拼单周期
      goodsInfo.linkcode = (this.data.data.linkcode ? this.data.data.linkcode : linkcode);//商品唯一32位id
      goodsInfo.attribute = e.detail.value;//商品属性
      goodsInfo.groupId = this.data.data.groupId;

      goodsInfo.titleArray = this.data.data.titleArray;
      goodsInfo.RecMark = this.data.data.RecMark;//推荐标记

      var addItem = JSON.stringify([goodsInfo]);
      var url = "/pages/hotel-order-confirm/hotel-order-confirm?goodsArr=" + addItem + "&roomtitle=" + goodsInfo.title + "&roomimage=" + goodsInfo.def_img + "&brtime=" + this.data.brtime + "&btype=" + this.data.btype;
      wx.navigateTo({ url: url});
    }
  },

 


  //跳转
  goAtherPage: function(e){
      var url = e.currentTarget.dataset.link;
      //如果是 立即购买 或 咨询 则需要判断是否已授权登录
      if (wxAuthFail && (url.indexOf('order-confirm') >= 0)){
        app.reAuthorize(this.reGetUserInfo);
        return;
      }

      var pageIndex = getCurrentPages().length;
      if(pageIndex >= 5){
        wx.redirectTo({ url: url, fail: function (e) { console.log(e) } })
      } else {
        wx.navigateTo({ url: url, fail: function (e) { console.log(e) } })
      }
  },
  clickImg: function(e){
      this.setData({
          "stv.src":e.currentTarget.dataset.imgsrc,
          "stv.display":"true"
      });
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },
  //跳转
  goAtherPageRelaunch: function (e) {
    var url = e.currentTarget.dataset.link;
    //如果是 立即购买 或 咨询 则需要判断是否已授权登录
    if (wxAuthFail && (url.indexOf('gouwuche/gouwuche') >= 0)) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
  },
  clickImg: function (e) {
    // this.setData({
    //     "stv.src":e.currentTarget.dataset.imgsrc,
    //     "stv.display":"true"
    // });
    var imgListType = e.currentTarget.dataset.imglist;
    var imgList = [];
    if (imgListType == "1"){
      var photo = this.data.data.photoscbk;
      for (var i = 0; i < photo.length ; i++){
        imgList = imgList.concat([photo[i].photo]);
      }
    } else if (imgListType == "2") {
      var photo = this.data.data.link_works;
      for (var i = 0; i < photo.length; i++) {
        imgList = imgList.concat(photo[i].photosData);
      }
    } else if (imgListType == "3") {
      var photo = this.data.data.link_relations;
      for (var i = 0; i < photo.length; i++) {
        imgList = imgList.concat(photo[i].photosData);
      }
    }
    console.log(imgList);
    wx.previewImage({
      current: e.currentTarget.dataset.imgsrc,
      urls: imgList
    })
  },

  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);
  },







  showEWMAV: function (e) {
    wx.previewImage({
      current: e.currentTarget.dataset.imgsrc,
      urls: [e.currentTarget.dataset.imgsrc]
    })
  },

  makeCallPhone: function (e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },


  
  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },


  



  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showAttribute: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showAttribute: true
      })
    }.bind(this), 200)
  },

  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showAttribute: false
      })
    }.bind(this), 200)
  },


  getghs: function () {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghswithscore",
      orgid: util.orgid,
      page: 1,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("供货商数据：", result);
        for (var i = 0; i < result.length; i++) {
          if (result[i].gcataid == that.data.data.gtype.substring(0, 3)) {
            var uid = result[i].uid;
            var title = result[i].username;
            if (result[i].subjectlist.length <2) {
              var existservice=false;
              var existenviroment=false;

              result[i].subjectlist.forEach(function(m,j){
                existservice=m.subject=='service'?true:false
                existenviroment = m.subject =='enviroment'?true:false
              })
              if (!existservice){
                result[i].subjectlist.push({ subject: 'service', score: 0 })
              }
              if (!existenviroment){
                result[i].subjectlist.push({ subject: 'enviroment', score: 0 })
              }

              console.log("result[i].subjectlist", result[i].subjectlist)
            }
            var distanStr = '';
            var distan = app.getDistance(that.data.userInfo.lat, that.data.userInfo.lon, result[i].lat, result[i].lon);
            if (distan > 1000) {
              distanStr = (distan / 1000).toFixed(2) + 'km';
            } else {
              distanStr = distan.toFixed(0) + 'm';
            }
            result[i].distanse = distanStr;
            result[i].distansenum = distan;
            that.setData({

              ghs: result[i],
              ghsid: result[i].uid,
              ghsname: result[i].username, 
              ghsgoodrate: (result[i].goodrate*100).toFixed(0),              
              ghsscore: (result[i].scorecoin / result[i].scorenum).toFixed(1),
              markers: [{
                id: 1,
                latitude: result[i].lat,
                longitude: result[i].lon,
                name: result[i].address
              }],
            });
            
          }
        }
      }
    });
  },



  goMapView: function (e) {
    var addr = e.currentTarget.dataset.addr;
    var lat = parseFloat(addr.lat);
    var lon = parseFloat(addr.lon);
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 20,
      name: addr.name,
      address: addr.address
    })
  },
  // postuserscore


  postUserScore: function (e) {

    console.log("e: ", e);
    var that = this;
    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var ac = 'postuserscore';
    var privatekey = utilMd5.hexMD5(uid + ac + token);//私钥
    var params = {
      ac: ac,
      privatekey: privatekey,
      postuid: that.data.ghsid,
      uid: uid,
      score:parseInt(e.detail.value)+1,
      subject:e.currentTarget.dataset.subject
    }
    var toastStr="点评成功！";
    console.log("postuserscore params: ", params);
    util.api({
      method: "POST",
      data: params,
      success: function (responseData) {
        console.log("点评", responseData.data);
        var result = responseData.data;
        if (result.res) {
          app.dialogToast(toastStr, 'success');
          that.getghs();
          console.log(toastStr, result);
        }
      }
    });
  },

  getAttributeForHotel:function(){
    var that=this;
    var group = this.data.data.groupId;
    var params = {
      publickey: util.publiccode,
      ac: "getAttribute",
      orgid: util.orgid,
      uid: that.data.uid,
      groupId: group
    };

    console.log("商品属性请求参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log("商品属性:", responseData.data);
        var result = responseData.data;
        if (result.length > 0) {
          var groups = [];
          for (var i = 0; i < result.length; i++) {
            var exist = false;
            if (i == 0) {
              let groupObj = { groupId: '', groupName: "", subList: [] };
              groupObj.groupId = result[i].groupId;
              groupObj.groupName = result[i].groupName;
              let subObj = {};
              subObj.attributeId = result[i].attributeId;
              subObj.attributeName = result[i].attributeName;
              subObj.checked = false;
              groupObj.subList.push(subObj);
              groups.push(groupObj);
              continue
            } else {
              for (var j = 0; j < groups.length; j++) {
                if (groups[j].groupId == result[i].groupId) {
                  let subObj = {};
                  subObj.attributeId = result[i].attributeId;
                  subObj.attributeName = result[i].attributeName;
                  subObj.checked = false;
                  groups[j].subList.push(subObj);
                  exist = true;
                  break
                }
              }
              if (!exist) {
                let groupObj = { groupId: '', groupName: "", subList: [] };
                groupObj.groupId = result[i].groupId;
                groupObj.groupName = result[i].groupName;
                let subObj = {};
                subObj.attributeId = result[i].attributeId;
                subObj.attributeName = result[i].attributeName;
                subObj.checked = false;
                groupObj.subList.push(subObj);
                groups.push(groupObj);
              }

            }


          }
          console.log('groups---->', groups);

          that.setData({
            childArr: [],
            attributeGroupsOriginal: result,
            attributeGroups: groups
          });
        }
      }
    });
  },

  getKucunToday: function (topicid) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getKucunToday",
      tc: that.data.tc,
      orgid: util.orgid,
      topicid: topicid,
      btime: that.getCurrentObj().getTime() / 1000
    };
    console.log("getKucunToday：", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log("getKucunToday：", responseData.data);
        var result = responseData.data.res;
        that.data.data.kucun = result;

        that.setData({
          data: that.data.data
        })
      }
    });
  },
  getCurrentObj: function () {
    var c_obj = new Date()
    var a = c_obj.getFullYear() + '/' + (c_obj.getMonth() + 1) + '/' + c_obj.getDate()
    return new Date(a)
    // return new Date(a).getTime() / 1000
  },
  hideAttribute: function () {
    var that = this;
    that.hideModal();
  },

})